package org.dromara.wmscloud.common.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.wmscloud.common.IAsyncService;
import org.dromara.wmscloud.constant.RedisConstants;
import org.dromara.wmscloud.domain.bo.BaseUnitBo;
import org.dromara.wmscloud.domain.vo.BaseUnitVo;
import org.dromara.wmscloud.service.IBaseUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 异步共通类实现类
 *
 * @author hou
 * @date 2025-04-04
 */
@Slf4j
@Service
public class AsyncServiceImpl implements IAsyncService {

    @Resource
    private IBaseUnitService baseUnitService;

    @PostConstruct
    public void init() {
        this.updateUnitToRedis();
    }

    @Async
    @Override
    public void updateUnitToRedis() {
        BaseUnitBo bo = new BaseUnitBo();
        bo.setStatus("Y");
        List<BaseUnitVo> list = baseUnitService.queryList(bo);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        RedisUtils.deleteObject(RedisConstants.UNITS_MEASURES_LIST_KEY);
        RedisUtils.setCacheList(RedisConstants.UNITS_MEASURES_LIST_KEY, list);
        list.forEach(item -> RedisUtils.setCacheObject(item.getUnitCode(), item.getUnitName()));
    }
    /**
     * 更新单位到redis
     * 可以选择是否需要先删除
     *
     * @param delete true代表需要先删除指定的key
     */
    @Override
    public void updateUnitToRedis(Boolean delete, List<String> keys) {
        // 如果需要删除
        if (delete){
            deleteUnitToRedis(keys);
        }
        // 更新单位到redis
        this.updateUnitToRedis();
    }
    /**
     * 删除redis种的单位
     */
    @Override
    public void deleteUnitToRedis(List<String> keys) {
        // 转为可变集合
        ArrayList<String> list = new ArrayList<>(keys);
        // 添加单位集合列表的key，一起删除
        list.add(RedisConstants.UNITS_MEASURES_LIST_KEY);
        RedisUtils.deleteObject(list);
    }
}
